/**
 * GTActivityViewController.m
 *
 * The contents of this file are subject to the Mozilla Public License Version 1.1 (the "License");
 * you may not use this file except in compliance with the License. You may obtain a copy of the License 
 * at http://www.mozilla.org/MPL/
 * Software distributed under the License is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY KIND,
 * either express or implied. See the License for the specific language governing rights and limitations 
 * under the License.
 *
 * The Original Code is gcast-toolbox4iphone.
 *
 * The Initial Developers of the Original Code is Giannandrea Castaldi.
 */

#import "GTActivityViewController.h"
#import "UIKit+GTExtensions.h"

static CGFloat const ACTIVITY_MESSAGE_WIDTH = 320.0;
static CGFloat const ACTIVITY_MESSAGE_WIDTH_REDUCTION_FOR_SIZE_COMPUTATION = 20.0;
static CGFloat const VERTICAL_SPACE_BETWEEN_COMPONENTS = 30.0;
static CGFloat const MAX_ACTIVITY_MESSAGE_HEIGHT = 400.0;

@interface GTActivityViewController ()
@property(nonatomic,retain) UIActivityIndicatorView *activityWheel;
@property(nonatomic,retain) UITextView *activityMessage;
@property(nonatomic,retain) UIButton *okButton;
- (void)repositionControlsWithOrientation:(UIInterfaceOrientation)toOrientation;
- (void)willRotate:(id)sender;
@end

@implementation GTActivityViewController
@synthesize activityWheel, activityMessage, okButton;

+ (id)viewController {
  return [[[self alloc] init] autorelease];
}

- (id)init {
    if ((self = [super init])) {
      [[NSNotificationCenter defaultCenter] addObserver:self
                                               selector:@selector(willRotate:)
                                                   name:UIApplicationWillChangeStatusBarOrientationNotification object:nil];
    }
    return self;
}

- (void)loadView {
  UIWindow *window = [[[UIApplication sharedApplication] delegate] window];
  
  // Activity view
  UIInterfaceOrientation orientation = [window.rootViewController interfaceOrientation];
  CGRect activityViewFrame = (UIDeviceOrientationIsPortrait(orientation) ?
                              CGRectMake(0.0, 0.0, window.bounds.size.width, window.bounds.size.height) :
                              CGRectMake(0.0, 0.0, window.bounds.size.height, window.bounds.size.width));
	self.view = [[[UIView alloc] initWithFrame:activityViewFrame] autorelease];
  self.view.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;
	self.view.backgroundColor = [UIColor blackColor];
  self.view.userInteractionEnabled = YES;
  
  // Activity wheel
  CGRect activityWheelRect = CGRectMake(0.0, 0.0, 30, 30);
  self.activityWheel = [[[UIActivityIndicatorView alloc] initFlexibleWithFrame:activityWheelRect
                                                    activityIndicatorViewStyle:UIActivityIndicatorViewStyleWhiteLarge] autorelease];
  self.activityWheel.center = CGPointMake(self.view.frame.size.width / 2, self.view.frame.size.height / 4);
	[self.view addSubview:self.activityWheel];
  
  // Activity message
  self.activityMessage = [[[UITextView alloc] initWithFrame:CGRectZero] autorelease];
  self.activityMessage.font = [UIFont fontWithName:@"Arial-Bold" size:17.0];
  self.activityMessage.textAlignment = UITextAlignmentCenter;
  self.activityMessage.backgroundColor = [UIColor clearColor];
  self.activityMessage.textColor = [UIColor whiteColor];
  self.activityMessage.editable = FALSE;
  self.activityMessage.scrollEnabled = FALSE;
  self.activityMessage.text = @"";
  [self.view addSubview:self.activityMessage];
  
  self.okButton = [UIButton buttonWithType:UIButtonTypeRoundedRect];
  self.okButton.frame = CGRectMake(0.0, 0.0, 200, 33.0);
  [self.okButton setTitle:@"OK" forState:UIControlStateNormal];
  [self.okButton addTarget:self action:@selector(okButtonPressed) forControlEvents:UIControlEventTouchUpInside];        
}

- (void)dealloc {
  [[NSNotificationCenter defaultCenter] removeObserver:self];
  [activityWheel stopAnimating];
  [activityWheel release];
  [activityMessage release];
  [okButton release];
  [super dealloc];
}

- (void)notifyStartActivity {
  [self notifyStartActivityWithAlpha:0.5f];
}

- (void)notifyStartActivityWithAlpha:(CGFloat)alpha {
  UIWindow *window = [[[UIApplication sharedApplication] delegate] window];
  UIInterfaceOrientation orientation = [window.rootViewController interfaceOrientation];  
  
	self.view.alpha = alpha;
	[window.rootViewController.view addSubview:self.view];
  [window.rootViewController.view bringSubviewToFront:self.view];  
  [self repositionControlsWithOrientation:orientation];
	[self.activityWheel startAnimating];  
}

- (void)notifyMessage:(NSString*)aMessage {
  if ([self.okButton superview]) {
    [self.okButton removeFromSuperview];
  }
  CGSize size = [aMessage sizeWithFont:self.activityMessage.font
                     constrainedToSize:CGSizeMake(ACTIVITY_MESSAGE_WIDTH - ACTIVITY_MESSAGE_WIDTH_REDUCTION_FOR_SIZE_COMPUTATION, MAX_ACTIVITY_MESSAGE_HEIGHT)
                         lineBreakMode:UILineBreakModeWordWrap];
  [self.activityMessage setFrame:CGRectMake(0.0, 0.0, ACTIVITY_MESSAGE_WIDTH, size.height + 20)];
  [self.activityMessage performSelectorOnMainThread:@selector(setText:) withObject:aMessage waitUntilDone:YES];
  [self.activityMessage performSelectorOnMainThread:@selector(setTextColor:) withObject:[UIColor whiteColor] waitUntilDone:YES];
  
  
  UIWindow *window = [[[UIApplication sharedApplication] delegate] window];
  UIInterfaceOrientation orientation = [window.rootViewController interfaceOrientation];
  [self repositionControlsWithOrientation:orientation];
}

- (void)notifyMessageToConfirm:(NSString*)aMessage {
  [self notifyMessage:aMessage];
  okButtonPressed = NO;
  self.okButton.center = CGPointMake(160.0,
                                     self.activityMessage.frame.origin.y + self.activityMessage.frame.size.height + VERTICAL_SPACE_BETWEEN_COMPONENTS);
  [self.view addSubview:self.okButton];
  
  NSRunLoop *theRL = [NSRunLoop currentRunLoop];
  while (!okButtonPressed && [theRL runMode:NSDefaultRunLoopMode beforeDate:[NSDate distantFuture]]);
}

- (void)okButtonPressed {
  okButtonPressed = YES;
}

- (void)notifyEndActivity {
  if (self.view.superview) {
    [self.view removeFromSuperview];
  }
}

- (void)willRotate:(id)sender {
	NSNotification *notification = sender;
	if (notification) {
    UIInterfaceOrientation toOrientation = [[notification.userInfo valueForKey:UIApplicationStatusBarOrientationUserInfoKey] integerValue];
    [self repositionControlsWithOrientation:toOrientation];
  }
}

- (void)repositionControlsWithOrientation:(UIInterfaceOrientation)toOrientation {
  UIWindow *window = [[[UIApplication sharedApplication] delegate] window];
  if (UIDeviceOrientationIsPortrait(toOrientation)) {
    self.activityMessage.center = CGPointMake(window.bounds.size.width/2, window.bounds.size.height/2);
  }
  else {
    self.activityMessage.center = CGPointMake(window.bounds.size.height/2, window.bounds.size.width/2);
  }
}

@end
